# coding=utf-8
# coding=utf-8
from __future__ import print_function, absolute_import

import time
from datetime import datetime, timedelta

from gm.api import *
import pandas as pd
import extend
import matplotlib.pyplot as plt
import matplotlib

from tools import dbTool


# 查看最终的回测结果
def on_backtest_finished(context, indicator):
    print(indicator)


def getIndexStock():
    df = stk_get_index_constituents("SHSE.000852")
    res = df[df['symbol'] == 'SHSE.600812']
    print(res)


def getIndexEndChange():
    df = history(symbol='SHSE.000852', frequency='1d', start_time='2024-01-01', end_time='2024-12-19',
                 fields='open, close, low, high, eob', adjust=ADJUST_PREV, df=True)
    dates = extend.third_friday(2024)
    dates2 = pd.to_datetime(dates).tz_localize("Asia/Shanghai")
    # 所有时间加上前一天
    dates3 = dates2 - pd.Timedelta(days=1)
    df2 = df[(df['eob'].isin(dates2)) | (df['eob'].isin(dates3))]
    df2['change'] = (df['close'] - df['close'].shift(1)) / df['close'].shift(1)
    df3 = df2[df2['eob'].isin(dates2)]
    avg = df3['change'].mean()
    print(avg)


def fun():
    print('run1')


def test_schedule():
    schedule(schedule_func=fun, date_rule='1d', time_rule='14:50:00')
    # schedule.every().day.at("09:30").do(getIndexEndChange)


def getBK():
    # res = get_history_symbol(symbol='BK.007001', start_date='2024-11-13', end_date='2024-12-14', df=True)
    res = get_history_symbol(symbol='BK.007413', start_date='2024-11-13', end_date='2024-12-14', df=True)
    res2 = get_history_symbol(symbol='BK.007004', start_date='2024-11-13', end_date='2024-12-24', df=True)
    # x = [1, 2, 3, 4, 5]  # X轴数据
    # y = [2, 3, 5, 7, 11]  # Y轴数据
    x = res2['trade_date']
    y = res2['pre_close']
    # matplotlib.use('Qt5Agg')
    matplotlib.use('TkAgg')
    plt.plot(x, y, marker='o')
    plt.title('示例折线图')  # 图表标题
    plt.xlabel('X轴标签')  # X轴标签
    plt.ylabel('Y轴标签')  # Y轴标签
    plt.grid(True)
    plt.show()


def getIndexCons():
    # res = stk_get_index_constituents(index='SHSE.000300')
    # res = stk_get_index_constituents(index='SHSE.000001')
    res = stk_get_index_constituents(index='SZSE.932000')
    # dbTool.saveAll('dt_company_20241223', res, '深圳上证成分股(SZSE.399106,SHSE.000001指数成分股)')
    # res2 = stk_get_index_constituents(index='SHSE.000001')
    # res = stk_get_index_constituents(index='SZSE.399106')
    # dbTool.saveAll('dt_company_20241223', res, '深圳上证成分股(SZSE.399106,SHSE.000001指数成分股)')
    print(res)


def getPrice():
    code = 'SZSE.159531'
    data = current([code], fields='', include_call_auction=False)
    history_data = history(symbol=code, frequency='60s', start_time='2024-12-24', end_time='2024-12-25',
                           fields='open, close, low, high, eob', adjust=ADJUST_PREV, df=True)
    print(data)
    print(history_data)


def monitorIndexTrend(context: Context):
    """监控指数趋势, 1=上升,0=不变,-1=下跌
    """
    code = 'SZSE.159531'  # 中证2000
    # 获取当前日期
    log(context, '开始检测指数趋势')
    now = context.now
    todayStr = now.strftime('%Y-%m-%d')
    after1Day = (now + timedelta(days=1)).strftime('%Y-%m-%d')
    pre1Day = (now - timedelta(days=1)).strftime('%Y-%m-%d')
    pre10Day = (now - timedelta(days=10)).strftime('%Y-%m-%d')
    historyMinuteData = history(symbol=code, frequency='60s', start_time=todayStr, end_time=after1Day,
                                fields='open, close, low, high, eob', adjust=ADJUST_PREV, df=True)
    historyDayData = history(symbol=code, frequency='1d', start_time=pre10Day, end_time=pre1Day,
                             fields='open, close, low, high, eob', adjust=ADJUST_PREV, df=True)
    preDayClosePrice = historyDayData['close'].iloc[-1]
    todayFirstPrice = historyMinuteData.iloc[0]
    todayEndPrice = historyMinuteData.iloc[-1]

    trend = 0
    # 交易日9:32分触发
    if preDayClosePrice > todayFirstPrice['open'] > todayFirstPrice['close'] > historyMinuteData.loc[1]['close']:
        trend = -1
    elif preDayClosePrice < todayFirstPrice['open'] < todayFirstPrice['close'] < historyMinuteData.loc[1]['close']:
        trend = 1
    if trend != 0:
        info(context, '指数趋势:', trend)
        if trend == 1 and todayFirstPrice['open'] < todayEndPrice['close']:
            print("right")
        if trend == -1 and todayFirstPrice['open'] > todayEndPrice['close']:
            print("right")
    else:
        log(context, '结束检测指数趋势')
    return trend


def info(context: Context, *args):
    print(context.now.strftime('%Y-%m-%d %H:%M:%S'), *args)


def log(context: Context, *args):
    if context.mode == MODE_LIVE:
        print(context.now.strftime('%Y-%m-%d %H:%M:%S'), *args)


def buy(context):
    print("algo execute")
    code = 'SHSE.601005'
    data = current([code], fields='', include_call_auction=False)
    print(data)
    for item in data:
        if item['symbol'] == code:
            # protect_price = item['open'] + item['close'] * 0.09
            protect_price = item['quotes'][4]['ask_p']
            # 以市价购买200股浦发银行股票， price为保护限价
            res = order_volume(symbol=code, volume=100, side=OrderSide_Buy, order_type=OrderType_Market_BOC,
                               position_effect=PositionEffect_Open, price=protect_price)
            print(res)


def init(context):
    # getIndexStock()
    # getIndexEndChange()
    # getBK()
    getIndexCons()
    # getPrice()
    # monitorIndexTrend(context)
    # 每日定时任务
    # schedule(schedule_func=monitorIndexTrend, date_rule='1d', time_rule='09:32:05')
    pass


def on_bar(context, bars):
    pass


if __name__ == '__main__':
    '''
        strategy_id策略ID, 由系统生成
        filename文件名, 请与本文件名保持一致
        mode运行模式, 实时模式:MODE_LIVE 回测模式:MODE_BACKTEST
        token绑定计算机的ID, 可在系统设置-密钥管理中生成
        backtest_start_time回测开始时间
        backtest_end_time回测结束时间
        backtest_adjust股票复权方式, 不复权:ADJUST_NONE前复权:ADJUST_PREV后复权:ADJUST_POST
        backtest_initial_cash回测初始资金
        backtest_commission_ratio回测佣金比例
        backtest_slippage_ratio回测滑点比例
        backtest_match_mode市价撮合模式，以下一tick/bar开盘价撮合:0，以当前tick/bar收盘价撮合：1
        '''
    # b40aa9ba-c11d-11ef-8a13-e8c829bed8c8
    run(strategy_id='14db9d1d-bdb8-11ef-8b1c-7486e210ef39',
        filename='testGM.py',
        mode=MODE_BACKTEST,
        token='fd322a3568282f2404e1602e95a8861fe5e36b00',
        backtest_start_time='2024-07-01 08:00:00',
        backtest_end_time='2024-12-26 16:00:00',
        backtest_adjust=ADJUST_PREV,
        backtest_initial_cash=10000000,
        backtest_commission_ratio=0.0001,
        backtest_slippage_ratio=0.0001,
        backtest_match_mode=1)
